<?php

class ObjectUtils
{
    /**
     *
     * @param object $instance
     * @param array|ArrayAccess $data
     * @return object
     */
    public static function populate( $instance, $data )
    {
        foreach ( $data as $prop => $val )
        {
            self::setProperty( $instance, $prop, $val );
        }

        return $instance;
    }

    /**
     *
     * @param object $instance
     * @param mixed $prop
     * @param mixed $val
     * @return mixed
     */
    public static function setProperty( $instance, $prop, $val )
    {
        $setter = self::constructSetterByProp( $prop );
        if ( method_exists( $instance, $setter ) )
        {
            $instance->$setter( $val );
        }
        else
        {
            $instance->$prop = $val;
        }
        return $val;
    }

    /**
     *
     * @param string $prop
     * @return string
     */
    public static function constructSetterByProp( $prop )
    {
        return "Set" . substr( strtoupper( $prop ), 0, 1 ) . substr( $prop, 1 );
    }
}